﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace GameView.Comment
{
    public static class TextBlockExtensions
    {
        public static readonly DependencyProperty EnableCopyProperty =
            DependencyProperty.RegisterAttached("EnableCopy", typeof(bool), typeof(TextBlockExtensions),
                new PropertyMetadata(false, OnEnableCopyChanged));

        public static bool GetEnableCopy(DependencyObject obj) => (bool)obj.GetValue(EnableCopyProperty);

        public static void SetEnableCopy(DependencyObject obj, bool value) => obj.SetValue(EnableCopyProperty, value);

        private static void OnEnableCopyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TextBlock textBlock)
            {
                if ((bool)e.NewValue)
                {
                    textBlock.ContextMenu = new ContextMenu();
                    textBlock.ContextMenu.Items.Add(new MenuItem
                    {
                        Header = "复制",
                        Command = ApplicationCommands.Copy,
                        CommandTarget = textBlock
                    });

                    // 添加鼠标左键双击复制
                    textBlock.MouseDown += (s, args) =>
                    {
                        if (args.ChangedButton == MouseButton.Left && args.ClickCount == 2)
                        {
                            Clipboard.SetText(textBlock.Text);
                        }
                    };
                }
                else
                {
                    textBlock.ContextMenu = null;
                }
            }
        }
    }
}